<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Gio_Db_Mysql
{
	public $_link;
	public $_host;
	public $_connected = false;
	public $_tablePrefix;
	public $_username;
	public $_password;
	public $_dbName;
	public $_port;
	
	private static $_instance = null;
	
	/**
	 * @return Gio_Db_Mysql
	 */
	public static function getInstance($instance = false)
	{
		if (null == self::$_instance) {
			self::$_instance = new self($instance);
		}
		return self::$_instance;
	}
	
	/**
	 * @return Gio_Db_Mysql
	 */
	public function __construct($instance = false)
	{
		if ($instance) {
			return $this;
		}
		$configs = Gio_Core_Config_Xml::getConfig('db');
				
		$this->_host 		= $configs->host;
		$this->_username 	= $configs->username;
		$this->_password 	= $configs->password;
		$this->_dbName 		= $configs->name;
		$this->_port 		= $configs->port;
		$this->_tablePrefix = $configs->table_prefix;
		
		$host = ($this->_port != null) ? $this->_host . ':' . $this->_port : $this->_host;
		$link = null;
		$connected = false;
		
		$connected = mysql_pconnect($host, $this->_username, $this->_password, $link) or die('Cannot connect to Database!');
				
		$this->_connected = $connected;
		$this->_link = $link;
		mysql_select_db($this->_dbName, $connected);
		mysql_query(sprintf("SET CHARACTER SET '%s'", 
							mysql_real_escape_string($configs->encoding)));
		return self::$_instance = $this;
	}
	
	public function close()
	{
		return @mysql_close();
	}
	
	function displayError() {
		return "Error: " . @mysql_error($this->_connected);
	}
	
	public function query($sql) {
		if (!$this->_connected) {
			return false;
		}
		
		$result =  @mysql_query($sql, $this->_connected);
		if  (!$result) {
			return $this->displayError();	
		}
		return $result;
	}

	public function fetchAll($result, $type = 'array') {
		switch($type) {
			case 'array':
				return @mysql_fetch_array($result, MYSQL_ASSOC);
				break;
			case 'object':
				return @mysql_fetch_object($result);
				break;
		}
	}

	public function count($result) {
		if (!$this->_connected) {
			return false;
		}
		return @mysql_num_rows($result);
	}

	public function lastInsertId()
	{
		if (!$this->_connected) {
			return false;
		}
		return @mysql_insert_id();
	}
	
	public function escape($string)
	{
		if(!$this->_link) { 
			return addslashes($string);
		}
		return mysql_real_escape_string($string);
	}
	
	public function freeResult($result)
	{
		return @mysql_free_result($result);
	}
	
	public function affectedRows()
	{
		return @mysql_affected_rows();
	}
	
	public function insert($data = array(), $tableName) {
		$sql = 'INSERT INTO ' . $tableName . ' (';
		$fields = null;
		$values = null;
		foreach ($data as $key => $value) {
			$fields .= (null == $fields) ? '' : ',';
			$fields .= $key;
			$values .= (null == $values) ? '' : ',';
			$values .= '"'. $this->escape($value) . '"';
		} 
				
		$sql .= $fields . ') VALUES ('.$values.')';
		$rs = $this->query($sql);
		/**
		 * Free result 
		 */
		$this->freeResult($rs);
		return $this->lastInsertId();
	}
	
	public function getVersion()
	{
		$rs   = $this->query('SELECT VERSION() AS ver LIMIT 1');
		$row  = mysql_fetch_object($rs);
		$this->freeResult($rs);
		return 'MySQL v' . $row->ver;
	}
	
	public function testConnection($config)
	{
		$link = @mysql_connect($config['host'] . ':' . $config['port'], $config['username'], $config['password']);
		if (!$link) {
			return false;
		}
		return true;
	}
	
	public function getDatabases($config)
	{
		if (!$this->testConnection($config)) {
			return array();
		}
		
		$databases = array();
		try {
			$rows 	   = mysql_list_dbs();
			while ($row = mysql_fetch_object($rows)) {
				$databases[] = $row->Database;
			}
		} catch (Exception $e) {}
		
		return $databases;
	}
}